package cn.com.dcsgo.controller;

import cn.com.dcsgo.pojo.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * DemoController
 *
 * @author Dcsgo
 * @since 2025/3/5 8:37
 */
@RestController
@RequestMapping
public class DemoController {
    @GetMapping("/exception/error1")
    public String error1() {
        throw new NullPointerException("DemoController.error1()");
    }

    @GetMapping("/exception/error2")
    public String error2() {
        throw new IllegalArgumentException("DemoController.error2()");
    }

    @GetMapping("interceptor")
    public String interceptor() {
        return "DemoController.interceptor()";
    }

    @GetMapping
    public String index() {
        return "Hello !";
    }

    /**
     * 参数效验
     * 通常传入的参数是一个类对象，要想使得效验规则生效必须使用@Validated注解修饰
     * json传参需要再通过@RequestBody修饰，parma则不需要(回忆一下@RequestParam和@RequestBody)
     * 效验失败会抛出异常，异常信息会返回给前端
     * 为了自定义处理异常，我们需要在效验参数的后面再加一个BindingResult类型的参数(两个参数之间不能有其他参数)
     *
     * @param user 效验规则通过在类的属性上添加效验注解实现
     * @return Object
     */
    @PostMapping("user/register")
    public Object register(@RequestBody @Validated User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            // 获取错误信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            StringBuilder errorMessages = new StringBuilder();
            for (FieldError fieldError : fieldErrors) {
                errorMessages.append("Field: ").append(fieldError.getField())
                        .append(", Error: ").append(fieldError.getDefaultMessage())
                        .append("; ");
            }

            HashMap<String, String> result = new HashMap<>();
            result.put("code", "400");
            result.put("msg", "Validation errors: " + errorMessages);
            return result;
        }
        return user;
    }
}
